<template>
  <div class="permission-container">
    <!-- 树形结构卡片 -->
    <el-card v-loading="loading" class="mb-4">
      <template #header>
        <div class="card-header">
          <span>权限树形图(系统级权限不支持修改)</span>
        </div>
        <div class="flex justify-end">
          <el-button class="mr-2" type="primary" @click="handleAddPermission">
            添加权限
          </el-button>
          <el-button class="mr-2" type="danger" @click="handleDeletePermission">
            删除权限
          </el-button>
        </div>
      </template>

      <el-tree
        :data="permissionTree"
        node-key="id"
        :props="{
          label: 'name',
          children: 'children'
        }"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <div class="permission-info">
              <span class="permission-name">{{ data.name }}</span>
              <el-tag size="small" type="info" class="permission-id">
                ID: {{ data.id }}
              </el-tag>
              <div class="hover-buttons">
                <el-tag
                  class="action-tag"
                  type="primary"
                  effect="plain"
                  @click.stop="handleEditPermission(data)"
                >
                  <el-icon class="icon"><Edit /></el-icon>
                  修改权限
                </el-tag>
                <el-tag
                  class="action-tag"
                  type="success"
                  effect="plain"
                  @click.stop="handleAddChildPermission(data)"
                >
                  <el-icon class="icon"><Plus /></el-icon>
                  添加子权限
                </el-tag>
              </div>
            </div>
            <div class="permission-description">
              {{ data.description }}
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 表格视图卡片 -->
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>权限列表</span>
        </div>
      </template>

      <el-table :data="flattenPermissions" border>
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="name"
          label="权限名称"
          min-width="200"
          header-align="center"
        >
          <template #default="{ row }">
            <div :style="{ paddingLeft: `${getIndent(row)}px` }">
              <el-icon v-if="row.pid !== -1"><Right /></el-icon>
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="描述"
          min-width="200"
          header-align="center"
        />
        <el-table-column
          prop="pid"
          label="父级ID"
          width="100"
          align="center"
          header-align="center"
        >
          <template #default="{ row }">
            <el-tag v-if="row.pid === -1" type="success">根节点</el-tag>
            <span v-else>{{ row.pid }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="创建时间"
          width="180"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="updated_at"
          label="更新时间"
          width="180"
          align="center"
          header-align="center"
        />
      </el-table>
    </el-card>

    <!-- 添加权限弹框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="currentEditId ? '修改权限' : '添加权限'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入权限名称，例如：table.user.sex"
          />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="addForm.description"
            placeholder="请输入权限描述，例如：用户表性别"
          />
        </el-form-item>
        <el-form-item label="父级ID" prop="pid">
          <el-input
            v-model="addForm.pid"
            type="number"
            placeholder="请输入父级ID，例如：34"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除权限弹框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除权限"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="deleteForm"
        :rules="deleteRules"
        label-width="100px"
      >
        <el-form-item label="权限ID" prop="permission_id">
          <el-input
            v-model="deleteForm.permission_id"
            type="number"
            placeholder="请输入要删除的权限ID，例如：44"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDeleteForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowRight as Right, Edit, Plus } from "@element-plus/icons-vue";
import { getAllPermisson, getMyPermissions } from "@/api/index";
import { addPermission, deletePermission, updatePermission } from "@/api/index";

// 权限数据接口
interface Permission {
  id: number;
  name: string;
  description: string;
  created_at: string;
  updated_at: string;
  pid: number;
  children?: Permission[];
}

// 弹框相关
const addDialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const formRef = ref();

// 添加权限表单
const addForm = reactive({
  name: "",
  description: "",
  pid: undefined as number | undefined
});

// 删除权限表单
const deleteForm = reactive({
  permission_id: undefined as number | undefined
});

// 表单校验规则
const addRules = {
  name: [{ required: true, message: "请输入权限名称", trigger: "blur" }],
  description: [{ required: true, message: "请输入权限描述", trigger: "blur" }],
  pid: [{ required: true, message: "请输入父级ID", trigger: "blur" }]
};

const deleteRules = {
  permission_id: [{ required: true, message: "请输入权限ID", trigger: "blur" }]
};

// 打开添加权限弹框
const handleAddPermission = () => {
  addDialogVisible.value = true;
  addForm.name = "";
  addForm.description = "";
  addForm.pid = undefined;
};

// 打开删除权限弹框
const handleDeletePermission = () => {
  deleteDialogVisible.value = true;
  deleteForm.permission_id = undefined;
};

// 提交添加权限
const submitAddForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let res;
        if (currentEditId.value) {
          // 编辑模式
          res = await updatePermission({
            ...addForm,
            id: currentEditId.value
          });
        } else {
          // 添加模式
          res = await addPermission(addForm);
        }

        if (res.status === "success") {
          ElMessage.success(
            currentEditId.value ? "修改权限成功" : "添加权限成功"
          );
          addDialogVisible.value = false;
          fetchPermissions(); // 刷新权限列表
          // 重置编辑模式
          currentEditId.value = undefined;
        }
      } catch (error) {
        console.error(
          currentEditId.value ? "修改权限失败:" : "添加权限失败:",
          error
        );
        ElMessage.error(currentEditId.value ? "修改权限失败" : "添加权限失败");
      }
    }
  });
};

// 提交删除权限
const submitDeleteForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await deletePermission(deleteForm.permission_id!);
        if (res.status === "success") {
          ElMessage.success("删除权限成功");
          deleteDialogVisible.value = false;
          fetchPermissions(); // 刷新权限列表
        }
      } catch (error) {
        console.error("删除权限失败:", error);
        ElMessage.error("删除权限失败");
      }
    }
  });
};

// 处理权限数据，构建树形结构
const buildPermissionTree = (permissions: Permission[]): Permission[] => {
  const permissionMap = new Map<number, Permission>();
  const result: Permission[] = [];

  // 先把所有权限放入 Map
  permissions.forEach(permission => {
    permissionMap.set(permission.id, { ...permission, children: [] });
  });

  // 构建树形结构
  permissions.forEach(permission => {
    const node = permissionMap.get(permission.id)!;
    if (permission.pid === -1) {
      // 根节点
      result.push(node);
    } else {
      // 子节点，添加到父节点的 children 中
      const parent = permissionMap.get(permission.pid);
      if (parent) {
        parent.children = parent.children || [];
        parent.children.push(node);
      }
    }
  });

  return result;
};

// 获取所有权限
const permissionTree = ref<Permission[]>([]);
const loading = ref(false);

// 计算属性：扁平化的权限列表
const flattenPermissions = ref<Permission[]>([]);

// 获取缩进距离
const getIndent = (row: Permission): number => {
  let level = 0;
  let currentId = row.pid;

  while (currentId !== -1) {
    level++;
    const parent = flattenPermissions.value.find(p => p.id === currentId);
    if (!parent) break;
    currentId = parent.pid;
  }

  return level * 20;
};

/**
 * 获取自己拥有的权限
 */
const fetchPermissions = async () => {
  loading.value = true;
  try {
    const res = await getAllPermisson();
    if (res.status === "success") {
      // 保存原始数据用于表格展示
      flattenPermissions.value = res.data;
      // 构建树形结构用于树形展示
      permissionTree.value = buildPermissionTree(res.data);
    }
  } catch (error) {
    console.error("获取权限失败:", error);
    ElMessage.error("获取权限失败");
  } finally {
    loading.value = false;
  }
};

// 编辑权限
const handleEditPermission = (data: Permission) => {
  addDialogVisible.value = true;
  addForm.name = data.name;
  addForm.description = data.description;
  addForm.pid = data.pid;
  // 标记当前是编辑模式
  currentEditId.value = data.id;
};

// 添加子权限
const handleAddChildPermission = (data: Permission) => {
  addDialogVisible.value = true;
  addForm.name = "";
  addForm.description = "";
  addForm.pid = data.id;
  // 重置编辑模式
  currentEditId.value = undefined;
};

// 当前正在编辑的权限ID
const currentEditId = ref<number>();

onMounted(() => {
  fetchPermissions();
});
</script>

<style lang="scss" scoped>
.permission-container {
  padding: 20px;

  .mb-4 {
    margin-bottom: 16px;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .custom-tree-node {
    position: relative;
    display: flex;
    flex: 1;
    flex-direction: column;
    gap: 4px;
    padding: 4px 0;

    .permission-info {
      display: flex;
      gap: 8px;
      align-items: center;

      .permission-name {
        font-weight: 500;
      }

      .permission-id {
        font-size: 12px;
      }

      .hover-buttons {
        position: absolute;
        top: 50%;
        right: 0;
        z-index: 1;
        display: none;
        padding: 4px 8px;
        transform: translateY(-50%);

        .action-tag {
          padding: 6px 12px;
          margin: 0 4px;
          font-size: 14px;
          cursor: pointer;
          background: transparent;
          border: none;

          .icon {
            margin-right: 4px;
            font-size: 14px;
            vertical-align: middle;
          }

          &:hover {
            opacity: 0.8;
          }
        }
      }
    }

    .permission-description {
      font-size: 12px;
      color: #666;
    }
  }

  :deep(.el-tree) {
    .el-tree-node__content {
      position: relative;
      height: auto;
      padding: 4px 0;

      &:hover {
        background-color: var(--el-fill-color-light);

        .hover-buttons {
          display: flex !important;
          gap: 8px;
          align-items: center;
        }

        .node-actions {
          opacity: 1;
        }
      }

      // 添加图标和文本的样式
      .custom-tree-node {
        display: flex;
        flex: 1;
        justify-content: space-between;
        padding-right: 8px;

        .node-label {
          display: flex;
          align-items: center;

          .el-icon {
            margin-right: 8px;
            font-size: 16px;
          }
        }

        .node-actions {
          display: flex;
          gap: 8px;
          opacity: 0;
          transition: opacity 0.3s ease;

          .el-button {
            padding: 4px 8px;
          }
        }
      }
    }

    // 选中节点样式
    .is-current > .el-tree-node__content {
      color: var(--el-color-primary);
      background-color: var(--el-color-primary-light-9);
    }
  }

  :deep(.el-table) {
    // 表格基础样式
    .cell {
      padding: 8px 0;
      line-height: 1.5;
    }

    // 表头样式
    .el-table__header {
      th {
        height: 50px;
        font-weight: bold;
        color: var(--el-text-color-primary);
        background-color: var(--el-fill-color-light);
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
